package com.cardbaobao.cardbabyclient.ui.activity;

import android.os.Bundle;
import android.support.v7.widget.GridLayoutManager;
import android.support.v7.widget.RecyclerView;
import android.text.TextUtils;
import android.view.View;
import android.view.ViewGroup;
import android.widget.ImageView;
import android.widget.LinearLayout;

import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONObject;
import com.cardbaobao.cardbabyclient.R;
import com.cardbaobao.cardbabyclient.api.Api;
import com.cardbaobao.cardbabyclient.buried.Google;
import com.cardbaobao.cardbabyclient.buried.Self;
import com.cardbaobao.cardbabyclient.buried.SelfUtils;
import com.cardbaobao.cardbabyclient.ui.activity.base.BaseActivity;
import com.cardbaobao.cardbabyclient.ui.activity.web.AgreementWebViewActivity;
import com.cardbaobao.cardbabyclient.ui.activity.web.EventWebViewActivity;
import com.cardbaobao.cardbabyclient.ui.adapter.CardDoProgressAdapter;
import com.cardbaobao.cardbabyclient.base.Constant;
import com.cardbaobao.cardbabyclient.callback.ItemClickedCallback;
import com.cardbaobao.cardbabyclient.controller.CommonJumpController;
import com.cardbaobao.cardbabyclient.model.Banner;
import com.cardbaobao.cardbabyclient.model.CreditCardBank;
import com.cardbaobao.cardbabyclient.model.result.BannerResult;
import com.cardbaobao.cardbabyclient.utils.ApplicationHelper;
import com.cardbaobao.cardbabyclient.buried.GoogleAnalyticsUtil;
import com.cardbaobao.cardbabyclient.utils.ImageLoaderUtil;
import com.cardbaobao.cardbabyclient.utils.JsonUtil;
import com.cardbaobao.cardbabyclient.utils.ScreenUtil;
import com.cardbaobao.cardbabyclient.utils.ToastUtil;
import com.cardbaobao.cardbabyclient.utils.URLUtil;
import com.cardbaobao.cardbabyclient.utils.UmengEventUtils;
import com.cardbaobao.cardbabyclient.widget.TitleBar;
import com.stx.xhb.xbanner.XBanner;

import java.util.HashMap;
import java.util.List;
import java.util.Map;

import butterknife.BindView;
import rx.Observable;
import rx.Subscriber;

/**
 * Created by Administrator on 2016/12/28.
 */
public class CardDoProgressActivity extends BaseActivity {
    @BindView(R.id.ll_container)
    LinearLayout llContainer;

    @BindView(R.id.title_bar)
    TitleBar titleBar;

    @BindView(R.id.xb_banner)
    XBanner xBanner;

    @BindView(R.id.recycler_view)
    RecyclerView recyclerView;

    private CardDoProgressAdapter adapter;

    @Override
    protected void initView(Bundle savedInstanceState) {

        mCurrentPageId= Self.Page.app_card_progress_page;

        titleBar.setLeftViewOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                finish();
            }
        });
        ViewGroup.LayoutParams layoutParams = xBanner.getLayoutParams();
        layoutParams.height = (int) (ScreenUtil.getScreenWidth() * 28 / 75.0f);
        xBanner.setLayoutParams(layoutParams);
        xBanner.setmAutoPalyTime(Constant.BANNER_INTERVAL_TIME);

        GridLayoutManager layoutManager =
                new GridLayoutManager(mContext, 4);
        recyclerView.setLayoutManager(layoutManager);
        adapter = new CardDoProgressAdapter(null);
        adapter.setItemClickedCallback(new ItemClickedCallback<CreditCardBank>() {
            @Override
            public void onItemClicked(CreditCardBank item) {
                toQueryCardProgress(item);
            }
        });
        recyclerView.setAdapter(adapter);
    }

    @Override
    protected void initData(Bundle savedInstanceState) {
        getBannerData();
        getBankList();
    }

    @Override
    protected int getLayoutId() {
        return R.layout.activity_crad_do_progress;
    }

    @Override
    protected void onResume() {
        super.onResume();
        UmengEventUtils.pageEvent(mContext,
                ApplicationHelper.getApplicationContext().getString(R.string.event_0x015));
        if (xBanner.getParent() != null) {
            xBanner.startAutoPlay();
        }
        GoogleAnalyticsUtil.setScreenName(Google.CARD_PROGRESS);
    }

    @Override
    protected void onPause() {
        super.onPause();
        if (xBanner.getParent() != null) {
            xBanner.stopAutoPlay();
        }
    }

    /**
     * 去查询办卡进度
     *
     * @param item
     */
    private void toQueryCardProgress(CreditCardBank item) {
        SelfUtils.buriedClickData(Self.Action.app_click_card_progress_item,
                Self.Action.app_click_card_progress_item_des,
                mEnterPageTime,
                mCurrentPageId,
                mPrePageId);
        initIntent();
        mIntent.setClass(mContext, AgreementWebViewActivity.class);
        mIntent.putExtra(AgreementWebViewActivity.WEB_TITLE_S, item.getNameShort() + "办卡进度查询");
        mIntent.putExtra(AgreementWebViewActivity.WEB_URL_S, item.getProgressUrl());
        mIntent.putExtra(AgreementWebViewActivity.WEB_TYPE_I, 9);
        mIntent.putExtra(PRE_PAGE_ID_S,mCurrentPageId);
        mContext.startActivity(mIntent);
    }

    /**
     * 获取banner数据
     */
    private void getBannerData() {
        Observable<String> observable= Api.getBannerData(Constant.GLB0315);
        observable.subscribe(new Subscriber<String>() {
            @Override
            public void onCompleted() {

            }

            @Override
            public void onError(Throwable e) {
                hideBanner();
                ToastUtil.showToast(ApplicationHelper.
                        getApplicationContext().
                        getString(R.string.string_request_server_fail));
            }

            @Override
            public void onNext(String s) {
                BannerResult bannerResult = JsonUtil.json2Object(s, BannerResult.class);
                if (bannerResult.getCode() == Constant.SUC_CODE) {
                    if (bannerResult.getData() != null) {
                        final List<Banner.CarouselFigureListBean> data =
                                bannerResult.getData().getCarousel_figure_list();
                        if (data != null && data.size() > 0) {
                            xBanner.stopAutoPlay();
                            xBanner.setData(data, null);
                            xBanner.setmAdapter(new XBanner.XBannerAdapter() {
                                @Override
                                public void loadBanner(XBanner banner, Object model, View view, int position) {
                                    ImageLoaderUtil.displayImage(URLUtil.CBB_IMG_URL + ((Banner.CarouselFigureListBean) model).getImage(),
                                            (ImageView) view);
                                }
                            });
                            xBanner.setOnItemClickListener(new XBanner.OnItemClickListener() {
                                @Override
                                public void onItemClick(XBanner banner, int position) {
                                    Banner.CarouselFigureListBean bean = data.get(position);
                                    if (!TextUtils.isEmpty(bean.getUrl())) {
                                        Map<String, String> adMap = new HashMap<>();
                                        adMap.put("banner_id", String.valueOf(bean.getDetail_id()));
                                        adMap.put("banner_url", bean.getUrl());
                                        UmengEventUtils.clickEvent(mContext, getString(R.string.event_0x040), adMap);
                                    }

                                    SelfUtils.buriedClickData(Self.Action.app_click_card_progress_top_banner,
                                            Self.Action.app_click_card_progress_top_banner_des,
                                            mEnterPageTime,
                                            mCurrentPageId,
                                            mPrePageId);

                                    CommonJumpController controller =
                                            new CommonJumpController(mContext);
                                    Map<String, Object> extra = new HashMap<>();
                                    extra.put(CommonJumpController.FROM_PAGE, "办卡进度-banner");
                                    extra.put(EventWebViewActivity.WEB_TYPE_I, 6);
                                    controller.bannerJump(bean, extra);
                                }
                            });
                            xBanner.startAutoPlay();
                        } else {
                            hideBanner();
                        }
                    } else {
                        hideBanner();
                    }
                } else {
                    hideBanner();
                    ToastUtil.showToast(bannerResult.getMsg());
                }
            }
        });
    }

    private void hideBanner() {
        llContainer.removeView(xBanner);
    }

    /**
     * 获取银行列表
     */
    private void getBankList() {
        showProgressDialog(false);
        Observable<String> observable=Api.getCardProgressBankList();
        observable.subscribe(new Subscriber<String>() {
            @Override
            public void onCompleted() {

            }

            @Override
            public void onError(Throwable e) {
                dismissProgressDialog();
                ToastUtil.showToast(ApplicationHelper.
                        getApplicationContext().
                        getString(R.string.string_request_server_fail));
            }

            @Override
            public void onNext(String s) {
                dismissProgressDialog();
                JSONObject json = JSON.parseObject(s);
                if (json.getIntValue("code") == Constant.SUC_CODE) {
                    List<CreditCardBank> data =
                            JSON.parseArray(json.getString("data"), CreditCardBank.class);
                    if (data != null && data.size() > 0) {
                        adapter.setData(data);
                        recyclerView.setAdapter(adapter);
                    }
                } else {
                    ToastUtil.showToast(json.getString("result"));
                }
            }
        });
    }
}
